﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gt.dotnetcore.webapi.extensions;
using gt.dotnetcore.webapi.extensions.ApiException;
using gt.dotnetcore.webapi.extensions.ApiLogging;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace gt.ApiGateway
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            Action<IdentityServerAuthenticationOptions> isaOpt = option =>
            {
                option.Authority = Configuration["IdentityService:Uri"];
                option.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]);
                option.ApiName = Configuration["IdentityService:ApiName"];
                //option.ApiSecret = Configuration["IdentityService:ApiSecret"];  //?作用是什么
                option.SupportedTokens = SupportedTokens.Jwt;
            };
            services.AddAuthentication()
                .AddIdentityServerAuthentication(Configuration["IdentityService:DefaultScheme"], isaOpt);

            //   与使用is4的区别，后者会自动给相应的Claims赋值以及相应的Authorize，jwt只负责认证
            //  services.AddAuthentication()
            //    .AddJwtBearer("Bearer", options =>
            //    {
            //        options.Authority = Configuration["IdentityService:Uri"];
            //        options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]);
            //        options.Audience = Configuration["IdentityService:ApiName"];
            //        //options. = Configuration["IdentityService:ApiSecret"];
            //    });

            services.AddOcelot(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseGlobalException();
            app.UseGlobalApiLogging();

            app.UseOcelot().Wait();
        }
    }
}
